import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import Handlebars from 'handlebars';
const templateCache = {};
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const loadTextFile = (relativePath) => fs.readFileSync(path.join(__dirname, relativePath), { encoding: 'utf8' })
Handlebars.registerHelper('json', context => {
    return new Handlebars.SafeString(JSON.stringify(context));
});
Handlebars.registerHelper('nextIndex', index => index + 1);

export const render = (promptFileName, renderData) => {
    const renderFunction = getTemplateRender(promptFileName);
    const result = renderFunction(renderData);
    return result;
}

const getTemplateRender = (fileName) => {
    const cache = templateCache[fileName];
    if (cache) {
        return cache;
    }
    const template = loadTextFile(`./${fileName}`);
    const renderFunction = Handlebars.compile(template);
    templateCache[fileName] = renderFunction;
    return renderFunction;
}